#pragma once
#include<iostream>
#include<cstdio>
#include<stdlib.h>
#include<cstring>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#define BACKLOG 5
class tcpServer
{
  private:
    int port;
    int lsock;
  public:
  tcpServer(int _port = 8080)
    :port(_port)
    ,lsock(-1)
  {}
 void initServer()
 {
    lsock = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in local;
    local.sin_family = AF_INET;
    local.sin_port = htons(port);
    local.sin_addr.s_addr = INADDR_ANY;

    if(bind(lsock,(struct sockaddr*)&local,sizeof(local)) < 0)
    {
       std::cerr<<"bind error"<<std::endl;
       exit(2);
    }
    if(listen(lsock,BACKLOG) < 0)
    {        
       std::cerr<<"listen error"<<std::endl;
       exit(3);
    }
 }
void server(int sock)
 {
   char buffer[1024];
   while(true)
   { 
     ssize_t s = recv(sock,buffer,sizeof(buffer)-1,0);
    if(s > 0)
    {
       buffer[s] = 0;
       std::cout<<"Client:"<<buffer<<std::endl;
    
       send(sock,buffer,strlen(buffer),0);
    }
    else if(s == 0)
    {
      std::cout<<"Client quit..."<<std::endl;
      break;
    }
    else 
    {
      std::cout<<"recv error"<<std::endl;
      break;
    }
  }
   close(sock);
}
 void start()
 {
    struct sockaddr_in endpoint;
    while(true)
    {
      socklen_t len = sizeof(endpoint);
     int sock = accept(lsock,(struct sockaddr*)&endpoint,&len);
     if(sock < 0)
     {
       std::cerr<<"accept error"<<std::endl;
       continue;
     }
      std::cout<<"get new a link"<<std::endl;
      server(sock);
    }
  }
~tcpServer()
{
  close(lsock);
}

};
